package com.run.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.run.common.utils.PageUtils;
import com.run.common.utils.Query;
import com.run.gulimall.product.dao.CategoryDao;
import com.run.gulimall.product.entity.CategoryEntity;
import com.run.gulimall.product.service.CategoryBrandRelationService;
import com.run.gulimall.product.service.CategoryService;
import com.run.gulimall.product.service.CategoryService;
import com.run.gulimall.product.vo.Catalog3Vo;
import com.run.gulimall.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     *  找到所有的商品并进行三级分类
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2、组装成父子的树形结构
        //2.1、找到所有的一级分类（根据数据库可知，父分类id为0为一级分类）
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == 0;
        }).map(menu ->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2) ->{
            return menu1.getSort() - menu2.getSort();
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO  1、检查当前删除的菜单，是否被别的地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override // CategoryServiceImpl
    public Long[] findCateLogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        paths = findParentPath(catelogId, paths);
        // 收集的时候是顺序 前端是逆序显示的 所以用集合工具类给它逆序一下
        // 子父 转 父子
        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]); // 1级  2级  3级
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @Transactional
    @Override

    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    @Override
    @Cacheable(value = {"category"},key = "'levelCategorys'")
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("查询数据库...");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }
    @Cacheable(value = "category",key = "#root.methodName")
    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        // 查询所有一级分类
        List<CategoryEntity> level1 = getLevel1Categorys();
        Map<String, List<Catelog2Vo>> parent_cid = level1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 拿到每一个一级分类 然后查询他们的二级分类
            List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catelog2Vo> catelog2Vos = null;
            if (entities != null) {
                catelog2Vos = entities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), l2.getName(), l2.getCatId().toString(), null);
                    // 找当前二级分类的三级分类
                    List<CategoryEntity> level3 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    // 三级分类有数据的情况下
                    if (level3 != null) {
                        List<Catalog3Vo> catalog3Vos = level3.stream().map(l3 -> new Catalog3Vo(l3.getCatId().toString(), l3.getName(), l2.getCatId().toString())).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //3、将数据放入缓存，将对象转为JSON放在缓存中
        String catalogJson = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("catalogJSON", catalogJson);
        return parent_cid;
    }

    public Map<String, List<Catelog2Vo>> getCatelogJson2() {

        //1、加入缓存逻辑
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        if (StringUtils.isEmpty(opsForValue.get("catalogJSON"))){
            //2、缓存中没有
            getCatelogJsonFromDbWithRedisLock();

        }
        //缓存中有，把JSON字符串逆转为能用的对象类型[反序列化]
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(opsForValue.get("catalogJSON"),new TypeReference<Map<String, List<Catelog2Vo>>>(){});

        return result;

    }

    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedisLock() {
        //1、占分布式锁。去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        if (lock){
            Map<String, List<Catelog2Vo>> dataFromDb = null;
            try {
                //加锁成功  执行业务
                System.out.println("获取分布式锁成功！");
                dataFromDb = getDataFromDb();
            }finally {
                //原子删锁
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] \n" +
                        "then\n" +
                        "\treturn redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end;\n";
                redisTemplate.execute(new DefaultRedisScript<Integer>(script,Integer.class)
                        ,Arrays.asList("lock"),uuid);

            }
            return dataFromDb;
        } else {
            //加锁失败 重试
            //减缓频率 休眠100ms
//            Thread.sleep(1000);
            System.out.println("获取分布式锁失败..等待中");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatelogJsonFromDbWithRedisLock();
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        if (!StringUtils.isEmpty(redisTemplate.opsForValue().get("catalogJSON"))) {
            //缓存中有，把JSON字符串逆转为能用的对象类型[反序列化]
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(redisTemplate.opsForValue().get("catalogJSON"), new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });

            return result;
        }
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        // 查询所有一级分类
        List<CategoryEntity> level1 = getLevel1Categorys();
        Map<String, List<Catelog2Vo>> parent_cid = level1.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            // 拿到每一个一级分类 然后查询他们的二级分类
            List<CategoryEntity> entities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
            List<Catelog2Vo> catelog2Vos = null;
            if (entities != null) {
                catelog2Vos = entities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), l2.getName(), l2.getCatId().toString(), null);
                    // 找当前二级分类的三级分类
                    List<CategoryEntity> level3 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                    // 三级分类有数据的情况下
                    if (level3 != null) {
                        List<Catalog3Vo> catalog3Vos = level3.stream().map(l3 -> new Catalog3Vo(l3.getCatId().toString(), l3.getName(), l2.getCatId().toString())).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catalog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //3、将数据放入缓存，将对象转为JSON放在缓存中
        String catalogJson = JSON.toJSONString(parent_cid);
        redisTemplate.opsForValue().set("catalogJSON", catalogJson);
        return parent_cid;
    }

    public Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithLocalLock() {
        return getDataFromDb();
    }

    /**
     *  从数据库中查询并封装数据[加锁防止缓存击穿]
     */
    public synchronized Map<String, List<Catelog2Vo>> getCatelogJsonFromDb() {
        return getDataFromDb();
    }

    /**
     * 递归收集所有父分类
     */
    private List<Long> findParentPath(Long catlogId, List<Long> paths) {
        // 1、收集当前节点id
        paths.add(catlogId);// 比如父子孙层级，返回的是 孙 子 父
        CategoryEntity parent_Id = this.getById(catlogId);
        if (parent_Id.getParentCid() != 0) {
            // 递归
            findParentPath(parent_Id.getParentCid(), paths);
        }
        return paths;
    }


    /**
     * 递归获取所有菜单的子菜单(包括子菜单的子菜单，直到全部被获取)
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().
                filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity ->{
            /**
             * 获取子菜单的子菜单（递归）
             */
            categoryEntity.setChildren(getChildrens(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2) ->{
            return menu1.getSort() - menu2.getSort();
        }).collect(Collectors.toList());
        return children;
    }
}